<?php

class ItsRetrievesController extends AppController {

    var $name = 'ItsRetrieves';
    var $viewPath = 'its/returns/its_retrieves';
    var $pageTitle = 'Customer Return Information';
    /**
     * IRH => ItsRetrieveHead
     * IR => ItsRetrieve
     * @array model ที่ใช้งาน
     */
    var $uses = array('IRH', 'IR', 'CRH', 'Product', 'CustProductSite', 'ProductSerial', 'RunningNo', 'Warehouse', 'CRS', 'RS', 'UserCoH');
    var $paginate = array(
        'IRH' => array(
            'order' => 'IRH.id DESC'
        )
    );

    function beforeFilter() {
        parent::beforeFilter();
        $this->set('parentNav', 'its_returns');
        $this->set('tabMenu', 'tabmenus/its/returns');
    }

    function display() {
        parent::display('IRH');
        $this->paginate['IRH']['contain'] = array('Customer', 'Site', 'CRH', 'RS');

        $this->_checkCustomerOnHand('IRH');

        $op = array(
            'customer_id' => '=',
        );
        $this->_paging('IRH', $op);
    }

    function save() {
        $is_success = true;
        $irh_id = null;
        if ($this->data['mode'] == 'add') {
            $is_success = $this->_save_return();
        } else { // mode == 'edit'
            $this->IRH->id = $this->data['IRH']['id'];
            $is_success = $this->IRH->saveField('remark', $this->data['IRH']['remark']);
            $is_success &= $this->IRH->saveField('collector_id', $this->Auth->user('id'));
        }

        if ($is_success) {
            $irh_id = $this->IRH->id;
            $this->Session->setFlash("Save succesfull.", 'flash/ok');
        } else {
            $this->Session->setFlash("Save fail !", 'flash/fail');
        }

        $this->data['IR'] = null;
        $this->setAction('view', $irh_id);
    }

    function _save_return() {
        $irh_id = null;
        // ตรวจสอบว่ามีรายการเข้ามาหรือไม่
        $is_success = true;
        if (!empty($this->data['IRH']['cust_return_head_id'])) {

//            debug($this->data);
//            $is_success = false;

            $this->IRH->query("BEGIN");
            ;

            // กำหนดข้อมูล CRH Return Head
            // Generate return no
            $year = $this->Utility->getThaiYear();
            $runno = $this->RunningNo->getNextStockNo(RunningNo::CUST_RETURN_TYPE, $year);
            $this->data['IRH']['retrieve_no'] = RunningNo::CUST_RETURN_TYPE . $year . '2' . $runno;
            $this->data['IRH']['collector_id'] = $this->Auth->user('id');

            // ถ้า accept return ต้องใส่ location มาด้วย
            if ($this->data['IRH']['retrieve_status_id'] == RS::ACCEPT_STATUS) {
                $this->ProductSerial->validate['location_id'] = array('rule' => 'notEmpty', 'message' => 'Please select a product serial location.');
            }
            if ($this->IRH->saveAll($this->data, array('validate' => 'first', 'atomic' => false)) == true) {    // ถ้าไม่ใช่จะ return array error field
                if ($this->data['IRH']['retrieve_status_id'] == RS::ACCEPT_STATUS) {
                    $is_success &= $this->_acceptReturn();
                } elseif ($this->data['IRH']['retrieve_status_id'] == RS::DECLINE_STATUS) {
                    $is_success &= $this->_declineReturn();
                }
            } else {
                $is_success = false;
            }

            if ($is_success) {
                $this->IRH->query("COMMIT");
                ;
            } else {
                $this->IRH->query("ROLLBACK");
                $this->passedArgs['cust_return_head_id'] = $this->data['IRH']['cust_return_head_id'];
            }
        } else {
            $this->data = null;
            return false;
        }
        return $is_success;
    }

    /**
     *
     * @return boolean accept สำหรับหรือไม่
     */
    function _acceptReturn() {
        $is_success = true;
        // update CRH ว่ามีการ Return
        $this->CRH->id = $this->data['IRH']['cust_return_head_id'];
        $this->CRH->saveField('cust_return_status_id', CRS::RETURNED);
        $this->CRH->saveField('vendor_document_no', $this->data['IRH']['vendor_document_no']);

        $irh_id = $this->IRH->id;
        foreach ($this->data['IR'] as $iR) {
            // Update Cust Product Site current stock
            $retrieve_qty = $iR['retrieve_qty'];
            $this->Product->id = $iR['product_id'];
            $current_stock = $this->Product->field('current_stock');
            $is_success &= $this->Product->saveField('current_stock', $current_stock + $retrieve_qty);

            // ดึงรายการ ITS Retrieve
            $this->IR->contain();
            $_ir = $this->IR->find('first', array(
                        'conditions' => array(
                            'IR.product_id' => $iR['product_id'],
                            'its_retrieve_head_id' => $irh_id
                        )
                            )
            );

            //                debug($ps);
            // คัดลอก ProductSerial เดิม มาใส่อันใหม่
            for ($i = 0; $i < $retrieve_qty; ++$i) {
                // ดึงรายการ ProductSerial ที่จะ return กลับเข้ามา
                $this->ProductSerial->contain();
                $ps = $this->ProductSerial->findById($iR['ProductSerial'][$i]['id']);
                $data = array();
                $data['ProductSerial']['id'] = null;
                $data['ProductSerial']['product_id'] = $_ir['IR']['product_id'];
                $data['ProductSerial']['serial_no'] = $ps['ProductSerial']['serial_no'];
                $data['ProductSerial']['other_information'] = $ps['ProductSerial']['other_information'];
                $data['ProductSerial']['cost'] = $ps['ProductSerial']['cost'];
                $data['ProductSerial']['its_stock_in_type'] = IR::ITS_STOCK_IN_TYPE;
                $data['ProductSerial']['its_stock_in_id'] = $_ir['IR']['id'];
                $data['ProductSerial']['location_id'] = $iR['ProductSerial'][$i]['location_id'];
                $data['ProductSerial']['stock_out_priority'] = $ps['ProductSerial']['stock_out_priority'];
                $data['ProductSerial']['is_active_flag'] = true;

                // update ProductSerial เดิมว่าใช้งานไม่ได้
                $this->ProductSerial->id = $ps['ProductSerial']['id'];
                $this->ProductSerial->saveField('is_active_flag', false);

                // บันทึก ProductSerial อันใหม่
                $this->ProductSerial->create();
                $is_success &= $this->ProductSerial->save($data);
//                debug($data);
            }
        }
        return $is_success;
    }

    /**
     *
     * @return boolean decline สำหรับหรือไม่
     */
    function _declineReturn() {
        $is_success = true;
        // update CRH ว่าไม่รับ return
        $this->CRH->id = $this->data['IRH']['cust_return_head_id'];
        $this->CRH->saveField('cust_return_status_id', CRS::DECLINE);
        $this->CRH->saveField('vendor_document_no', $this->data['IRH']['vendor_document_no']);

        $irh_id = $this->IRH->id;
        foreach ($this->data['IR'] as $iR) {
            // Update Cust Product Site current stock
            $retrieve_qty = $iR['retrieve_qty'];
            $cust_product_site_id = $this->CustProductSite->field('id', array('product_id' => $iR['product_id'], 'site_id' => $this->data['IRH']['site_id']));
            $this->CustProductSite->id = $cust_product_site_id;
            $current_stock = $this->CustProductSite->field('current_stock');
            $is_success &= $this->CustProductSite->saveField('current_stock', $current_stock + $retrieve_qty);

            // ดึงรายการ ITS Retrieve
            $this->IR->contain();
            $_ir = $this->IR->find('first', array(
                        'conditions' => array(
                            'IR.product_id' => $iR['product_id'],
                            'its_retrieve_head_id' => $irh_id
                        )
                            )
            );

            // คัดลอก ProductSerial เดิม มาใส่อันใหม่
            for ($i = 0; $i < $retrieve_qty; ++$i) {
                // ดึงรายการ ProductSerial ที่จะ return กลับเข้ามา
                $this->ProductSerial->contain();
                $ps = $this->ProductSerial->findById($iR['ProductSerial'][$i]['id']);

                $data = array();
                $data['ProductSerial']['id'] = null;
                $data['ProductSerial']['product_id'] = $ps['ProductSerial']['product_id'];
                $data['ProductSerial']['serial_no'] = $ps['ProductSerial']['serial_no'];
                $data['ProductSerial']['other_information'] = $ps['ProductSerial']['other_information'];
                $data['ProductSerial']['cost'] = $ps['ProductSerial']['cost'];
                $data['ProductSerial']['its_stock_in_type'] = $ps['ProductSerial']['its_stock_in_type'];
                $data['ProductSerial']['its_stock_in_id'] = $ps['ProductSerial']['its_stock_in_id'];
                $data['ProductSerial']['location_id'] = $ps['ProductSerial']['location_id'];
                $data['ProductSerial']['stock_out_priority'] = $ps['ProductSerial']['stock_out_priority'];
                $data['ProductSerial']['is_active_flag'] = true;

                $data['ProductSerial']['cust_product_site_id'] = $ps['ProductSerial']['cust_product_site_id'];
                $data['ProductSerial']['its_stock_out_type'] = $ps['ProductSerial']['its_stock_out_type'];
                $data['ProductSerial']['its_stock_out_id'] = $ps['ProductSerial']['its_stock_out_id'];
                $data['ProductSerial']['cust_location_id'] = $ps['ProductSerial']['cust_location_id'];
                $data['ProductSerial']['cust_stock_in_type'] = $ps['ProductSerial']['cust_stock_in_type'];
                $data['ProductSerial']['cust_stock_in_id'] = $ps['ProductSerial']['cust_stock_in_id'];
                $data['ProductSerial']['price'] = $ps['ProductSerial']['price'];

                $data['ProductSerial']['quote_price_valid_to'] = $ps['ProductSerial']['quote_price_valid_to'];
                $data['ProductSerial']['price_adjustment_case'] = $ps['ProductSerial']['price_adjustment_case'];
                $data['ProductSerial']['adjusted_price_1'] = $ps['ProductSerial']['adjusted_price_1'];
                $data['ProductSerial']['price_adjustment_1_date'] = $ps['ProductSerial']['price_adjustment_1_date'];
                $data['ProductSerial']['price_adjustment_1_valid_to'] = $ps['ProductSerial']['price_adjustment_1_valid_to'];
                $data['ProductSerial']['adjusted_price_2'] = $ps['ProductSerial']['adjusted_price_2'];
                $data['ProductSerial']['price_adjustment_2_date'] = $ps['ProductSerial']['price_adjustment_2_date'];
                $data['ProductSerial']['price_adjustment_2_valid_to'] = $ps['ProductSerial']['price_adjustment_2_valid_to'];
                $data['ProductSerial']['cust_purchase_date'] = $ps['ProductSerial']['cust_purchase_date'];
                $data['ProductSerial']['price_case_id'] = $ps['ProductSerial']['price_case_id'];

                // update ProductSerial เดิมว่าใช้งานไม่ได้
                $this->ProductSerial->id = $ps['ProductSerial']['id'];
                $this->ProductSerial->saveField('is_active_flag', false);

                // บันทึก ProductSerial อันใหม่
                $this->ProductSerial->create();
                $is_success &= $this->ProductSerial->save($data);
//                debug($data);
            }
        }
        return $is_success;
    }

    function view($id = null) {
        if ($id != null) {

            $this->IRH->contain(array('Customer', 'Site', 'CRH', 'Warehouse', 'RS', 'IR' => array('Product' => array('Unit'))));
            $this->data = $this->IRH->findById($id);

            $this->_neighbors($id, $this->IRH, array('fields' => array('id')));
            $this->set('mode', 'edit');
        } else {
            // ดึงรายการ Customer Return Head ที่ยังไม่ได้ทำการ retrieve
            $this->set('crhs', $this->CRH->find('list', array(
                        'conditions' => array(
                            'cust_return_status_id' => CRS::RETURNING
                        )
                            )
                    )
            );

            if (isset($this->passedArgs['cust_return_head_id'])) {
                $this->CRH->contain(array('Customer', 'Site',
                    'CR' => array('Product' => array('Unit'), 'ProductSerial')
                        )
                );

                $this->data = $this->CRH->findById($this->passedArgs['cust_return_head_id']);
            }

            $this->set('retrieveStatuses', $this->RS->find('list'));
            $this->set('warehouses', $this->Warehouse->find('list'));
            $this->set('retrieve_by', $this->Auth->user('name'));
            $this->set('today', date("d/m/Y"));
            $this->set('mode', 'add');
        }
    }

    function print_view($id) {
        $this->layout = 'print';
        $this->IRH->id = $id;

        // ถ้า accept reutrn
        if ($this->IRH->field('retrieve_status_id') == RS::ACCEPT_STATUS) {

            $this->data = $this->IRH->findForPrintById($id);
            $this->render('print_view');
        } else { // decline
            $this->IRH->contain(array('Customer', 'Site', 'Warehouse', 'CRH', 'RS',
                'IR' => array('Product' => array('part_no', 'text', 'Unit'), 'CustProductSite' => array('stock_code', 'price'))
            ));
            $this->data = $this->IRH->findById($id);
            $this->render('print_view_decline');
        }
    }

}

?>